{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 10 10\n"
     ]
    }
   ],
   "source": [
    "from selenium import webdriver\n",
    "import re\n",
    "import pandas as pd\n",
    "\n",
    "def x_news(x_words):\n",
    "\t# setting chrome\n",
    "\tchrome_options = webdriver.ChromeOptions()\n",
    "\tchrome_options.add_argument('--headless')\n",
    "\tchrome_options.add_argument('--disable-gpu')\n",
    "\tchrome_options.add_argument(\"window-size=1024,768\")\n",
    "\tchrome_options.add_argument(\"--no-sandbox\")\n",
    "\n",
    "\t# get url\n",
    "\tbrowser = webdriver.Chrome(options = chrome_options)\n",
    "\turl = 'http://search.sina.com.cn/?q=' + x_words + '&c=news&sort=time'\n",
    "\tbrowser.get(url)\n",
    "\n",
    "\tdata = browser.page_source\n",
    "\t# print(data)\n",
    "\tbrowser.quit()\n",
    "\n",
    "\tr_href = '<div class=\"box-result clearfix\".*?<a href=\"(.*?)\" target=\"_blank\">.*?</a>'\n",
    "\tr_title = '<div class=\"box-result clearfix\".*?<a href=\".*?\" target=\"_blank\">(.*?)</a>'\n",
    "\tr_date = '<span class=\"fgray_time\">(.*?)</span>'\n",
    "\n",
    "\threfs = re.findall(r_href, data, re.S)\n",
    "\ttitles = re.findall(r_title, data, re.S)\n",
    "\tdates = re.findall(r_date, data)\n",
    "\tprint(len(hrefs), len(titles), len(dates))\n",
    "\n",
    "\tfor i in range(len(hrefs)):\n",
    "\t\ttitles[i] = re.sub('<.*?>', '', titles[i])\n",
    "\n",
    "\t\tdates[i] = dates[i].split(' ')[1]\n",
    "\t\t# print(f'{i+1}.{titles[i]} | {dates[i]}')\n",
    "\t\t# print(hrefs[i])\n",
    "\n",
    "\tdata = pd.DataFrame({'标题': titles, '日期': dates, '链接': hrefs})\n",
    "# \tprint(data)\n",
    "\tdata.to_excel(x_words + '新浪新闻.xlsx', index=False)\n",
    "\n",
    "\n",
    "x_news('比亚迪')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
